import { useUserStore } from '@/pinia/modules/user'
import { useRouterStore } from '@/pinia/modules/router'
import getPageTitle from '@/utils/page'
import router from '@/router'

const asyncRouterFlag = 0

const whiteList = ['Login', 'Init','404','loginCas','loginError'] // 不需要登录就能进入的页面

router.beforeEach(async(to, from, next) => {
  
  const userStore = useUserStore()
  document.title = getPageTitle(to.meta.title, to)
  if(to.matched.length===0){
    next({ path: '/404'})
  }else if(whiteList.indexOf(to.name) > -1){ // 在白名单中的判断情况(无需登录)
      next()
  }else{
      if(!userStore.token || !userStore.userInfo.nickName){ // 未登录
        next({ path: '/login',query:{error_info:''}, replace: true })
      }else{ // 已登录
        const historyComponents = userStore.historys
        const pItem = historyComponents.find(item => item.name == to.name) // 查找当前页面是否存在historyComponents中
        if (pItem) {
          userStore.setPageInit(false)
        } else { // 说明页面不在标签页里面，需要初始化页面
          userStore.setPageInit(true)
        }
        next()
      }
  }
  
})
